<?php
// ----------------------------------------------------------
// * @Copyright @ 2011-2020 By HuaXiaXinCai
// ----------------------------------------------------------
// * @Author Yang Changwu<800334@qq.com> 2016-12-12
// ----------------------------------------------------------
namespace Controller;
use \GatewayWorker\Lib\Gateway;
use \GatewayWorker\Lib\Db;
use \Workerman\Lib\Timer;

class Core {
    protected $config;
    protected $playrules;
    protected $db;
    protected $globalinfo;

    public function __construct() {
        global $config, $playrules, $db, $globalinfo;
        $db = $this->db = Db::instance('db');
        $this->config = $this->db->select('*')->from('sz_config')->row();
        //大转盘信息
        $activity_roulette = $this->db->select('id,name,icon,awardtype,awardgift')->from('sz_activity')->where("type=1 and status=1")->query();
        
        //大转盘玩过总次数
        $roulette_sum = $this->db->select('count(id) as sum')->from('sz_activity_log')->where("activity_type=1 and activity_id not in ('4,5,6,14')")->row();
        
        $globalinfo = [
            'activity_roulette' => $activity_roulette,
            'roulette_sum'      => $roulette_sum['sum'],
        ];
        $playrules = [
            1 => [
                'name' => '和值',
                'select' => [1, 2], //1单选 2复选 3全选 4复式
                'value' => [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
                'award' => [
                    4 => [112],
                    5 => [113, 122],
                    6 => [114, 123, 222],
                    7 => [115, 124, 133, 223],
                    8 => [116, 125, 134, 224, 233],
                    9 => [126, 135, 144, 225, 234, 333],
                    10 => [136, 145, 226, 235, 244, 334],
                    11 => [146, 155, 236, 245, 335, 344],
                    12 => [156, 246, 255, 336, 345, 444],
                    13 => [166, 256, 346, 355, 445],
                    14 => [266, 356, 446, 455],
                    15 => [366, 456, 555],
                    16 => [466, 556],
                    17 => [566],
                ],
                'odds' => [40, 20, 12.5, 8, 6, 5, 4.5, 4.5, 5, 6, 8, 12.5, 20, 40], //单选,复选赔率一样
                'multiple' => 99999999,
            ],
            2 => [
                'name' => '二同号',
                'select' => [1, 2],
                'value' => [112, 113, 114, 115, 116, 122, 223, 224, 225, 226, 133, 233, 334, 335, 336, 144, 244, 344, 445, 446, 155, 255, 355, 455, 556, 166, 266, 366, 466, 566],
                'award' => [
                    11 => [112, 113, 114, 115, 116], 
                    22 => [122,223, 224, 225, 226],
                    33 => [133, 233,334, 335, 336],
                    44 => [144, 244, 344,445, 446],
                    55 => [155, 255, 355, 455,556],
                    66 => [166, 266, 366, 466, 566],
                ],
                'odds' => [40, 7.5], //单选 40,复选 7.5
                'multiple' => 99999999,
            ],
            3 => [
                'name' => '二不同号',
                'select' => [2],
                'value' => [12, 13, 14, 15, 16, 23, 24, 25, 26, 34, 35, 36, 45, 46, 56],
                'award' => [
                    12 => [112,122,123,124,125,126],
                    13 => [113,123,133,134,135,136],
                    14 => [114,124,134,144,145,146],
                    15 => [115,125,135,145,155,156],
                    16 => [116,126,136,146,156,166],
                    23 => [123,223,233,234,235,236],
                    24 => [124,224,234,244,245,246],
                    25 => [125,225,235,245,255,256],
                    26 => [126,226,236,246,256,266],
                    34 => [134,234,334,344,345,346],
                    35 => [135,235,335,345,355,356],
                    36 => [136,236,336,346,356,366],
                    45 => [145,245,345,445,455,456],
                    46 => [146,246,346,446,456,466],
                    56 => [156,256,356,456,556,566],
                ],
                'odds' => [4], //复选 4
                'multiple' => 99999999,
            ],
            4 => [
                'name' => '三同号',
                'select' => [1],
                'value' => [111, 222, 333, 444, 555, 666],
                'award' => [111, 222, 333, 444, 555, 666],
                'odds' => [120], //单选 120
                'multiple' => 99999999,
            ],
            5 => [
                'name' => '三同号全选',
                'select' => [3],
                'value' => [111, 222, 333, 444, 555, 666],
                'award' => [111, 222, 333, 444, 555, 666],
                'odds' => [20], //全选 20
                'multiple' => 99999999,
            ],
            6 => [
                'name' => '三不同号',
                'select' => [1,4],
                'value' => [123, 124, 125, 126, 134, 135, 136, 145, 146, 156, 234, 235, 236, 245, 246, 256, 345, 346, 356, 456],
                'award' => [123, 124, 125, 126, 134, 135, 136, 145, 146, 156, 234, 235, 236, 245, 246, 256, 345, 346, 356, 456],
                'odds' => [20], //单选 复式 20
                'multiple' => 99999999,
            ],
            7 => [
                'name' => '三连号全选',
                'select' => [3],
                'value' => [123, 234, 345, 456],
                'award' => [123, 234, 345, 456],
                'odds' => [5], //全选 5
                'multiple' => 99999999,
            ],
            8 => [
                'name' => '大',
                'select' => [1],
                'value' => [11, 12, 13, 14, 15, 16, 17, 18],
                'award' => [146, 155, 156, 166, 236, 245, 246, 255, 256, 266, 335, 336, 344, 345, 346, 355, 356, 366, 444, 445, 446, 455, 456, 466, 555, 556, 566, 666],
                'odds' => [2], //单选
                'multiple' => 99999999,
            ],
            9 => [
                'name' => '小',
                'select' => [1],
                'value' => [3, 4, 5, 6, 7, 8, 9, 10],
                'award' => [111, 112, 113, 114, 115, 116, 122, 123, 124, 125, 126, 133, 134, 135, 136, 144, 145, 222, 223, 224, 225, 226, 233, 234, 235, 244, 333, 334],
                'odds' => [2], //单选
                'multiple' => 99999999,
            ],
            10 => [
                'name' => '单',
                'select' => [1],
                'value' => [3, 5, 7, 9, 11, 13, 15, 17],
                'award' => [111, 113, 115, 122, 124, 126, 133, 135, 144, 146, 155, 166, 223, 225, 234, 236, 245, 256, 333, 335, 344, 346, 355, 366, 445, 456, 555, 566],
                'odds' => [2], //单选
                'multiple' => 99999999,
            ],
            11 => [
                'name' => '双',
                'select' => [1],
                'value' => [4, 6, 8, 10, 12, 14, 16, 18],
                'award' => [112, 114, 116, 123, 125, 134, 136, 145, 156, 222, 224, 226, 233, 235, 244, 246, 255, 266, 334, 336, 345, 356, 444, 446, 455, 466, 556, 666],
                'odds' => [2], //单选
                'multiple' => 99999999,
            ],
        ];
    }

    //发送信息
    public static function SendMsg($status = 1002, $data = array(), $send_type = 1, $client_id = '') {
        $error_msg = [
            1001 => '成功',
            1002 => '数据错误', //Data error
            1003 => '数据为空', //Data empty
            1004 => '签名错误', //Sign error
            1005 => '未知错误', //Unknown error
            1006 => '渠道商错误', //Channel error
            1007 => '用户名错误', //Username error
            1008 => '用户名重复', //Repeat username
            1009 => '昵称重复', //Repeat nickname
            1010 => '当前用户禁止登录', //Username access denied
            1011 => '当前用户在线', //Username online
            1012 => '当前在其他地方登录', //Login in other places
            1013 => '订单号错误', //Order number error
            1014 => '订单号重复', //Repeat order
            1015 => '投注期次错误', //Periodid error
            1016 => '投注时间结束', //Betting time over
            1017 => '投注金额错误', //Money error
            1018 => '投注串为空', //Betting code empty
            1019 => '投注串错误', //Betting code error
            1020 => '投注玩法错误', //Play error
            1021 => '投注选择类型错误', //单选 复选 全选 复式 Select type error
            1022 => '投注倍数错误', //Multiple error
            1023 => '账户金额不足', //Less account balance
            1024 => '网络连接异常断开', //Network connection exception
            1025 => '数据不存在', //Database record empty
            1026 => '奖励已领取', //Award has been received
            1027 => '商品不存在',
            1028 => '商品库存不足',
            1029 => '购买兑换失败',
        ];
        $message = [
            'status' => $status,
            'data' => $data,
            'msg' => $error_msg[$status],
        ];
        if ($send_type == 1) {
            Gateway::sendToCurrentClient(json_encode($message));//发送给当前客户端
        } else if($send_type == 2) {
            GateWay::sendToClient($client_id, json_encode($message));//发送指定客户端$client_id
        }else if($send_type == 3){
            GateWay::sendToUid($client_id,json_encode($message)); //发送绑定客户端$username
        }else{
            Gateway::sendToAll(json_encode($message));//发送所有客户端
        }
    }
    
    //倒记时推送
    public static function PushPeriod() {
        //初始化数据库连接
        $db = Db::instance('db');
        Timer::add(1, function()use($db) {
            //获取配置
            $config = $db->select('awardpool')->from('sz_config')->row();
            //查询当前期次
            $period = $db->select('*')->from('sz_period')->where('status=0 or status=2')->orderByASC(array('id'), false)->row();
            //下注倒记时
            $bettime = $period['endtime'] - time() - $period['awardtime'] - $period['exchangetime'];
            if ($bettime > 0) {
                $msg = [
                    'method' => 'Period',
                    'timetype' => 'bet',
                    'periodid' => $period['periodid'],
                    //'begintime' => $period['begintime'],
                    'pool' => $config['awardpool'],
                    'backtime' => $bettime,
                ];
                self::SendMsg(1001,$msg,4);
            } else {
                //开奖倒记时
                $awardtime = $period['endtime'] - time() - $period['awardtime'];
                if ($awardtime > 0) {
                    $msg = [
                        'method' => 'Period',
                        'timetype' => 'award',
                        'periodid' => $period['periodid'],
                        'awardnumber' => $period['awardnumber'],
                        'pool' => $config['awardpool'],
                        'backtime' => $awardtime,
                    ];
                    self::SendMsg(1001,$msg,4);
                    //兑奖推送
                    $betorder =$db->select('*,sum(winmoney) as sumwinmoney')->from('sz_betorder')->where("periodid='".$period['periodid']."' and awardstatus>0")->groupBy(array('username'))->query();
                    foreach ($betorder as $value){
                        if(Gateway::isUidOnline($value['username']) == 1){
                            $msg = [
                                'method' => 'Exchange',
                                'periodid' => $value['periodid'],
                                'winmoney' => $value['sumwinmoney'],
                            ];
                            Gateway::sendToUid($value['username'], json_encode(array('status'=>1001,'data'=>$msg,'msg'=>'成功')));
                        }
                    }
                } else {
                    //兑奖倒记时
                    $exchangetime = $period['endtime'] - time();
                    if ($exchangetime > 0) {
                        $msg = [
                            'method' => 'Period',
                            'timetype' => 'exchange',
                            'periodid' => $period['periodid'],
                            //'begintime' => $period['begintime'],
                            'awardnumber' => $period['awardnumber'],
                            'pool' => $config['awardpool'],
                            'backtime' => $exchangetime,
                        ];
                        self::SendMsg(1001,$msg,4);
                    }
                    if($exchangetime == 2){
                        //中奖排行推送
                        //$ranking = $db->select('username,winmoney')->from('sz_betorder')->orderByASC(array('winmoney'),false)->limit(10)->query();
                        $rankingsql = "SELECT b.nickname as username,a.winmoney FROM `sz_betorder` as a JOIN sz_user as b where a.username = b.username order by a.winmoney desc LIMIT 10";
                        $ranking = $db->query($rankingsql);
                        $msg = [
                            'method' => 'Notice',
                            'type' => 'top',
                            'data' => $ranking,
                        ];
                        self::SendMsg(1001,$msg,4);
                    }
                }
            }
        });
    }
    //公告推送
    public static function Notice(){
        //初始化数据库连接
        $db = Db::instance('db');
        $notice = $db->select('*')->from('sz_notice')->where("begintime<=".time()." and status=1")->query();
        foreach ($notice as $value){
            //发送所有用户
            if($value['owner'] == 'all'){
                if($value['endtime'] >= time()){
                    $system_notice_.$vlaue['id'] = Timer::add($value['cycle'], function()use($value){
                        $msg = [
                            'method' => 'Notice',
                            'type' => 'system',
                            'data' => [
                                'title' => $value['title'],
                                'content'=> $value['content'],
                            ],
                        ];
                        //print_r($msg);
                        self::SendMsg(1001,$msg,4);
                    });
                }else{
                    Timer::del($system_notice_.$vlaue['id']);
                }
            }
        }
    }
    
    //用户定时器
    public static function UserTimer($username){
        global $db;
        Timer::add(10, function()use($db,$username) {
            $loginday = intval((strtotime(date('Y-m-d',time()) . ' 00:00:01')-strtotime(date('Y-m-d',$_SESSION['logintime']).' 00:00:00'))/(60*60*24));
            if($loginday <= 7){
                //在线奖励计算
                self::OnlineAwardRun($db,$username);
                //新奖励推送
                self::PushOnlineAward($db,$username);
            }
            //更新在线时间
            self::UpdateOnlineTime($db,$username);
            //充值信息推送
            self::PushPay($db, $username);
        });
    }


    //更新在线时间
    public function UpdateOnlineTime($db,$username){
        if($_SESSION['uid']){
            //更新在线时间(秒)
            $sqluser = "UPDATE sz_user SET dayline = dayline+10 WHERE username='$username'";
            $_SESSION['dayline']+=10;
            $db->query($sqluser);
        }
    }
    
    //计算在线奖励
    public static function OnlineAwardRun($db,$username){
        $OnlineActivity = $db->select('id,name,conditionvalue,awardtype,awardgift')->from('sz_activity')->where("type=2 and status=1")->query();
        foreach ($OnlineActivity as $value) {
            if($_SESSION['dayline'] - $value['conditionvalue'] > 0 ){
                $award = [
                    'username'=> $username,
                    'activity_type'=> 2,
                    'activity_id'=> $value['id'],
                    'activity_name'=> $value['name'],
                    'awardtype'=> $value['awardtype'],
                    'awardgift'=> $value['awardgift'],
                    'addtime'=> time(),
                    'status' =>0,
                ];
                
                //每天在线奖励
                $today1 = strtotime(date('Y-m-d',time()) . ' 00:00:00');
                $today2 = strtotime(date('Y-m-d',time()) . ' 23:59:59');
                $activity_id = $value['id'];
                $onlineaward = $db->select('id,username,activity_id')->from('sz_activity_log')->where("username='$username' and activity_id=$activity_id and addtime between $today1 and $today2")->row();
                if(!$onlineaward){
                   $award['id'] = $db->insert('sz_activity_log')->cols($award)->query();
                }
            }
        }
    }
    
    //推送在线奖励
    public static function PushOnlineAward($db,$username){
        $today1 = strtotime(date('Y-m-d',time()) . ' 00:00:00');
        $today2 = strtotime(date('Y-m-d',time()) . ' 23:59:59');
        $onlineaward = $db->select('id')->from('sz_activity_log')->where("username='$username' and activity_type=2 and addtime between $today1 and $today2 and status=0")->query();
        if($onlineaward){
            $msg = ['method'=>'NewAward'];
            self::SendMsg(1001,$msg,3,$username);
        }else{
            $msg = ['method'=>'OnlineAwardPeriod'];
            self::SendMsg(1001,$msg,3,$username);
        }
    }
    
    //推送充值信息
    public static function PushPay($db,$username){
        $payrecord = $db->select('gold')->from('sz_pay')->where("username='$username' and status=0")->query();
        if($payrecord){
            foreach ($payrecord as $value) {
                $sum +=$value['gold'];
            }
            //增加金币
            $sqluser = "UPDATE `sz_user` SET gold = gold+$sum WHERE username='$username'";
            $db->query($sqluser);
            
            //修改订单状态
            $sqlpay = "UPDATE `sz_pay` SET status = 1 WHERE username='$username'";
            $db->query($sqlpay);
            
            //修改总充值总额
            $sqlconfig = "UPDATE sz_config SET paysum = paysum+$sum where id=1";
            $db->query($sqlconfig);
            
            $msg = [
                'method' => 'NewPay',
                'gold' => $sum,
            ];
            self::SendMsg(1001,$msg,3,$username);
        }
    }

    //获取期次
    public static function GetPeriod($periodid) {
        global $db;
        return $db->select('*')->from('sz_period')->where("periodid='$periodid' and status=0")->row();
    }

    //计算投注串
    public static function CastCount($castcodes) {
        global $db, $playrules;
        $codes = explode(';', $castcodes);
        foreach ($codes as $v) {
            $singlecodes = explode(':', $v);
            switch ($singlecodes[2]) {
                //和值
                case 1:
                    $betcodes = explode(',', $singlecodes[0]);
                    foreach ($betcodes as $value) {
                        $value = (int)$value;
                        //中奖号码
                        $award_array = $playrules[$singlecodes[2]]['award'][$value];

                        //赔率
                        $oddskey = array_search($value, $playrules[$singlecodes[2]]['value']);
                        $odds = $playrules[$singlecodes[2]]['odds'][$oddskey];

                        //计算投注金额
                        $betmoney = $singlecodes[3];

                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        foreach ($award_array as $v) {
                            $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$v";
                            $db->query($sql);
                        }
                    }
                    break;
                //二同号
                case 2:
                    $betcodes = explode(',', $singlecodes[0]);
                    sort($betcodes);
                    //单选 格式 1,6,1:1:2:10 号码161 单选类型 1  玩法二同号 2 倍数 10
                    if ($singlecodes[1] == 1) {
                        //中奖号码
                        foreach ($betcodes as $v){
                            $v = (int)$v;
                            $award .= $v;
                        }
                        $award = $award;

                        //赔率
                        $odds = $playrules[$singlecodes[2]]['odds'][0];

                        //计算投注金额
                        $betmoney = $singlecodes[3];

                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$award";
                        $db->query($sql);
                        unset($award);
                    }
                    //复选 11,22,33:2:2:10 号码11 22 33  复选类型 2  玩法二同号 2 倍数 10
                    if ($singlecodes[1] == 2) {
                        foreach ($betcodes as $v){
                            $v = (int)$v;
                            //中奖号码
                            $award_array = $playrules[$singlecodes[2]]['award'][$v];
                            
                            //赔率
                            $odds = $playrules[$singlecodes[2]]['odds'][1];
                            
                            foreach ($award_array as $val){
                                //计算投注金额
                                $betmoney = $singlecodes[3];

                                //计算中奖金额
                                $awardmoney = $singlecodes[3] * $odds;

                                //更新数据库
                                $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                                $db->query($sql);
                            }
                        }
                    }
                    break;
                //二不同号
                case 3:
                    //复选 格式 12,13,14:2:3:10 号码12 13 14 复选类型 2  玩法二不同号 3 倍数 10
                    $betcodes = explode(',', $singlecodes[0]);
                    foreach ($betcodes as $v){
                        $v = (int)$v;
                        //中奖号码
                        $award_array = $playrules[$singlecodes[2]]['award'][$v];

                        //赔率
                        $odds = $playrules[$singlecodes[2]]['odds'][0];

                        foreach ($award_array as $val){
                            //计算投注金额
                            $betmoney = $singlecodes[3];

                            //计算中奖金额
                            $awardmoney = $singlecodes[3] * $odds;

                            //更新数据库
                            $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                            $db->query($sql);
                        }
                    }
                    break;
                //三同号
                case 4:
                    //单选 格式 1,1,1:1:4:10 号码111 单选类型 1  玩法三同号 4 倍数 10
                    $betcodes = explode(',', $singlecodes[0]);
                    foreach ($betcodes as $v){
                        $v = (int)$v; 
                        //中奖号码
                        $award .= $v;
                    }
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];

                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    //计算中奖金额
                    $awardmoney = $singlecodes[3] * $odds;

                    //更新数据库
                    $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$award";
                    $db->query($sql);
                    unset($award);
                    break;
                //三同号全选
                case 5:
                    //全选 格式 00:3:5:10 号码00 全选类型 3  玩法三同号全选 5 倍数 10
                    //中奖号码
                    $award_array = $playrules[$singlecodes[2]]['award'];
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];
                    
                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    foreach ($award_array as $val){
                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                        $db->query($sql);
                    }
                    break;
                //三不同号
                case 6:
                    $betcodes = explode(',', $singlecodes[0]);
                    sort($betcodes);
                    //单选 格式 1,2,3:1:6:10 号码1,2,3 单选类型 1  玩法三不同号 6 倍数 10
                    if ($singlecodes[1] == 1) {
                        foreach ($betcodes as $v) {
                            $v = (int) $v;
                            //中奖号码
                            $award .= $v;
                        }
                        //赔率
                        $odds = $playrules[$singlecodes[2]]['odds'][0];

                        //计算投注金额
                        $betmoney = $singlecodes[3];

                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$award";
                        $db->query($sql);
                        unset($award);
                    }
                    //复式 格式 1,2,3,4:4:6:10 号码1,2,3,4 复式类型 4  玩法三不同号 6 倍数 10
                    if ($singlecodes[1] == 4) {
                        //开奖号码
                        $betstr = [];
                        foreach ($betcodes as $v) {
                            $v = (int) $v;
                            array_push($betstr, $v);
                        }
                        $award_array = self::RankCombin($betstr, 3,'');
                        
                        //赔率
                        $odds = $playrules[$singlecodes[2]]['odds'][0];
                        
                        //计算投注金额
                        $betmoney = $singlecodes[3];
                        
                        foreach ($award_array as $val){
                            //计算中奖金额
                            $awardmoney = $singlecodes[3] * $odds;

                            //更新数据库
                            $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                            $db->query($sql);
                        }
                    }
                    break;
                //三连号全选
                case 7:
                    //全选 格式 00:3:7:10 号码00 全选类型 3  玩法三连号全选 7 倍数 10
                    //中奖号码
                    $award_array = $playrules[$singlecodes[2]]['award'];
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];
                    
                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    foreach ($award_array as $val){
                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                        $db->query($sql);
                    }
                    break;
                //大 格式 00:1:8:10 号码00所有 单选类型 1  玩法大 8 倍数 10
                case 8:
                    //中奖号码
                    $award_array = $playrules[$singlecodes[2]]['award'];
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];
                    
                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    foreach ($award_array as $val){
                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                        $db->query($sql);
                    }
                    break;
                //小
                case 9:
                    //中奖号码
                    $award_array = $playrules[$singlecodes[2]]['award'];
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];
                    
                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    foreach ($award_array as $val){
                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                        $db->query($sql);
                    }
                    break;
                //单
                case 10:
                    //中奖号码
                    $award_array = $playrules[$singlecodes[2]]['award'];
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];
                    
                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    foreach ($award_array as $val){
                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                        $db->query($sql);
                    }
                    break;
                //双
                case 11:
                    //中奖号码
                    $award_array = $playrules[$singlecodes[2]]['award'];
                    //赔率
                    $odds = $playrules[$singlecodes[2]]['odds'][0];
                    
                    //计算投注金额
                    $betmoney = $singlecodes[3];

                    foreach ($award_array as $val){
                        //计算中奖金额
                        $awardmoney = $singlecodes[3] * $odds;

                        //更新数据库
                        $sql = "UPDATE `sz_betsum` SET `frequency` = frequency+1,`betmoney` = betmoney+$betmoney,`awardmoney` = awardmoney+$awardmoney WHERE betnumber=$val";
                        $db->query($sql);
                    }
                break;
            }
        }
    }

    //检查投注串
    public static function CheckCast($castcodes, $checkmoney) {
        global $playrules;
        $codes = explode(';', $castcodes);
        foreach ($codes as $v) {
            $singlecodes = explode(':', $v);
            //投注串
            if (count($singlecodes) < 4 || count($singlecodes) > 4) {
                return 1019;
            }
            //投注玩法
            if (!$playrules[$singlecodes[2]]) {
                return 1020;
            }
            //投注选择类型
            if (!in_array($singlecodes[1], $playrules[$singlecodes[2]]['select'])) {
                return 1021;
            }
            //投注倍数
            if ($singlecodes[3] > $playrules[$singlecodes[2]]['multiple'] || $singlecodes[3] < 1) {
                return 1022;
            }
            switch ($singlecodes[2]) {
                //和值
                case 1:
                    $playrules1 = explode(',', $singlecodes[0]);
                    //单选 格式 4:1:1:10 号码4 单选类型 1  玩法和值 1 倍数 10
                    if ($singlecodes[1] == 1) {
                        //判断单选
                        if (count($playrules1) > 1) {
                            return 1019;
                        }
                        //判断值
                        if (!in_array($playrules1[0], $playrules[$singlecodes[2]]['value'])) {
                            return 1019;
                        }
                        //计算投注金额
                        $money[1][1] += $singlecodes[3];
                    }
                    if ($singlecodes[1] == 2) {
                        //多选  格式 4,16,17,15:2:1:10 号码4 16 17 单选类型 2  玩法和值 1 倍数 10
                        if (count($playrules1) <= 1) {
                            return 1019;
                        }
                        //判断值
                        foreach ($playrules1 as $v) {
                            if (!in_array($v, $playrules[$singlecodes[2]]['value'])) {
                                return 1019;
                            }
                        }
                        //计算投注金额
                        $money[1][2] += count($playrules1) * $singlecodes[3];
                    }
                    break;
                //二同号
                case 2:
                    $playrules2 = explode(',', $singlecodes[0]);
                    sort($playrules2);
                    //单选 格式 1,6,1:1:2:10 号码161 单选类型 1  玩法二同号 2 倍数 10
                    if ($singlecodes[1] == 1) {
                        //判断单选
                        if (count($playrules2) != 3) {
                            return 1019;
                        }
                        foreach ($playrules2 as $v) {
                            $v = (int) $v;
                            $playrules2_value .= $v;
                        }

                        //判断值
                        if (!in_array($playrules2_value, $playrules[$singlecodes[2]]['value'])) {
                            return 1019;
                        }
                        unset($playrules2_value);
                        //计算投注金额
                        $money[2][1] += $singlecodes[3];
                    }
                    //复选 11,22,33:2:2:10 号码11 22 33  复选类型 2  玩法二同号 2 倍数 10
                    if ($singlecodes[1] == 2) {
                        //判断复选
                        foreach ($playrules2 as $v) {
                            $v = (int) $v;
                            //判断值  长度 = 2
                            if (strlen($v) != 2) {
                                return 1019;
                            }
                            //判断值 第一个值 = 第二个值
                            if ((int) substr($v, 0, 1) != (int) substr($v, -1) || (int) substr($v, 0, 1) > 6 || (int) substr($v, 0, 1) < 1 || (int) substr($v, -1) > 6 || (int) substr($v, -1) < 1) {
                                return 1019;
                            }
                        }
                        //计算投注金额
                        $money[2][2] += count($playrules2) * $singlecodes[3];
                    }
                    break;
                //二不同号
                case 3:
                    //复选 格式 12,13,14:2:3:10 号码12 13 14 复选类型 2  玩法二不同号 3 倍数 10
                    $playrules3 = explode(',', $singlecodes[0]);
                    sort($playrules3);
                    //判断值
                    foreach ($playrules3 as $v) {
                        $v = (int) $v;
                        //判断值  长度 = 2
                        if (strlen($v) != 2) {
                            return 1019;
                        }
                        //判断值
                        if (!in_array($v, $playrules[$singlecodes[2]]['value'])) {
                            return 1019;
                        }
                    }
                    //计算投注金额
                    $money[3][2] += count($playrules3) * $singlecodes[3];
                    break;
                //三同号
                case 4:
                    //单选 格式 1,1,1:1:4:10 号码111 单选类型 1  玩法三同号 3 倍数 10
                    $playrules4 = explode(',', $singlecodes[0]);
                    foreach ($playrules4 as $v) {
                        $v = (int) $v;
                        $playrules4_value .= $v;
                    }
                    //判断值
                    if (!in_array($playrules4_value, $playrules[$singlecodes[2]]['value'])) {
                        return 1019;
                    }
                    unset($playrules4_value);
                    //计算投注金额
                    $money[4][1] += $singlecodes[3];
                    break;
                //三同号全选
                case 5:
                    //全选 格式 00:3:5:10 号码00 全选类型 3  玩法三同号全选 5 倍数 10
                    $playrules5 = (int) $singlecodes[0];
                    if ($playrules5 != 0) {
                        return 1019;
                    }
                    //计算投注金额
                    $money[5][3] += $singlecodes[3];
                    break;
                //三不同号
                case 6:
                    $playrules6 = explode(',', $singlecodes[0]);
                    sort($playrules6);
                    //单选 格式 1,2,3:1:6:10 号码1,2,3 单选类型 1  玩法三不同号 6 倍数 10
                    if ($singlecodes[1] == 1) {
                        if (count($playrules6) != 3) {
                            return 1019;
                        }
                        foreach ($playrules6 as $v) {
                            $v = (int) $v;
                            $playrules6_value .= $v;
                        }
                        //判断值
                        if (!in_array($playrules6_value, $playrules[$singlecodes[2]]['value'])) {
                            return 1019;
                        }
                        unset($playrules6_value);
                        //计算投注金额
                        $money[6][1] += $singlecodes[3];
                    }
                    //复式 格式 1,2,3,4:4:6:10 号码1,2,3,4 复式类型 4  玩法三不同号 6 倍数 10
                    if ($singlecodes[1] == 4) {
                        if (count($playrules6) <= 3 || count($playrules6) > 6) {
                            return 1019;
                        }
                        $playrules62_value = [];
                        //判断复式
                        foreach ($playrules6 as $v) {
                            $v = (int) $v;
                            if ($v > 6) {
                                return 1019;
                            }
                            array_push($playrules62_value, $v);
                        }

                        $playrules62 = self::RankCombin($playrules62_value, 3);

                        //计算投注金额
                        $money[6][2] += count($playrules62) * $singlecodes[3];
                        unset($playrules62);
                        unset($playrules62_value);
                    }
                    break;
                //三连号全选
                case 7:
                    //全选 格式 00:3:7:10 号码00 全选类型 3  玩法三连号全选 7 倍数 10
                    $playrules7 = (int) $singlecodes[0];
                    if ($playrules7 != 0) {
                        return 1019;
                    }
                    //计算投注金额
                    $money[7][3] += $singlecodes[3];
                    break;
                //大 格式 00:1:8:10 号码00所有 单选类型 1  玩法大 8 倍数 10
                case 8:
                    $playrules8 = (int) $singlecodes[0];
                    if ($playrules8 != 0) {
                        return 1019;
                    }
                    //计算投注金额
                    $money[8][1] += $singlecodes[3];
                    break;
                //小
                case 9:
                    $playrules9 = (int) $singlecodes[0];
                    if ($playrules9 != 0) {
                        return 1019;
                    }
                    //计算投注金额
                    $money[9][1] += $singlecodes[3];
                    break;
                //单
                case 10:
                    $playrules10 = (int) $singlecodes[0];
                    if ($playrules10 != 0) {
                        return 1019;
                    }
                    //计算投注金额
                    $money[10][1] += $singlecodes[3];
                    break;
                //双
                case 11:
                    $playrules11 = (int) $singlecodes[0];
                    if ($playrules11 != 0) {
                        return 1019;
                    }
                    //计算投注金额
                    $money[11][1] += $singlecodes[3];
                    break;
                default:
                    return 1020;
                    break;
            }
            //投注总额
            $summoney += $singlecodes[3];
        }
//        foreach ($money as $v) {
//            $summoney += array_sum($v);
//        }
        if ($summoney != (int) $checkmoney) {
            return 1017 . $summoney;
        }
    }

    /**
      +----------------------------------------------------------
     * 排列组合无重复
     * 默认长度3位
      +----------------------------------------------------------
     * @param array		$array 排序数组
     * @param integer	$len 长度
     * @param string	$joint 拼接字符
      +----------------------------------------------------------
     * @return array
      +----------------------------------------------------------
     */
    public function RankCombin($array = [1, 2, 3, 4, 5, 6], $len = 3, $joint = ',') {
        $result = array();
        if ($len == 1) {
            return $array;
        }
        if ($len == count($array)) {
            $result[] = implode($joint, $array);
            return $result;
        }
        $temp_firstelement = $array[0];
        unset($array[0]);
        $array = array_values($array);
        $temp_list1 = self::RankCombin($array, ($len - 1), $joint);
        foreach ($temp_list1 as $s) {
            $s = $temp_firstelement . $joint . $s;
            $result[] = $s;
        }
        unset($temp_list1);
        $temp_list2 = self::RankCombin($array, $len, $joint);
        foreach ($temp_list2 as $s) {
            $result[] = $s;
        }
        unset($temp_list2);
        return $result;
    }

    /**
      +----------------------------------------------------------
     * 排列组合所有
     * 默认长度3位
      +----------------------------------------------------------
     * @param array		$arr 排序数组
     * @param integer	$len 长度
     * @param string 	$joint 拼接字符
      +----------------------------------------------------------
     * @return array
      +----------------------------------------------------------
     */
    public function RankCombinAll($array = [1, 2, 3, 4, 5, 6], $len = 3, $joint = ',') {
        if ($len == 1) {
            return $array;
        }
        $result = array();
        $tmpArr = $array;
        //unset($tmpArr[0]); 
        for ($i = 0; $i < count($array); $i++) {
            $s = $array[$i];
            $ret = self::RankCombinAll(array_values($tmpArr), ($len - 1), $joint);

            foreach ($ret as $row) {
                $result[] = $s . $joint . $row;
            }
        }
        return $result;
    }

    /**
      +----------------------------------------------------------
     * 排序去掉重复
      +----------------------------------------------------------
     * @param array 	$array 排序数组
     * @param string 	$unstr 解开字符
     * @param string 	$joint 拼接字符
      +----------------------------------------------------------
     * @return array
      +----------------------------------------------------------
     */
    public function RankCombinUnique($array, $unstr = ',', $joint = '') {
        foreach ($array as $v) {
            $arr = explode($unstr, $v);
            sort($arr);
            $temp[] = implode($joint, $arr);
        }
        $result = array_unique($temp);
        sort($result);
        return $result;
    }

    /**
      +----------------------------------------------------------
     * 产生随机字串，可用来自动生成密码
     * 默认长度6位 字母和数字混合 支持中文
      +----------------------------------------------------------
     * @param string $len 长度
     * @param string $type 字串类型
     * 0 字母 1 数字 其它 混合
     * @param string $addChars 额外字符
      +----------------------------------------------------------
     * @return string
      +----------------------------------------------------------
     */
    public static function RandString($len = 6, $type = '', $addChars = '') {
        $str = '';
        switch ($type) {
            case 0:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 1:
                $chars = str_repeat('0123456789', 3);
                break;
            case 2:
                $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' . $addChars;
                break;
            case 3:
                $chars = 'abcdefghijklmnopqrstuvwxyz' . $addChars;
                break;
            case 4:
                $chars = 'ABCDEFGHJKLMNPQRSTUVWXY' . $addChars;
                break;
            case 5:
                $chars = 'ABCDEFGHJKLMNPQRSTUVWXY1234567890' . $addChars;
                break;
            default :
                // 默认去掉了容易混淆的字符oOLl和数字01，要添加请使用addChars参数
                $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789' . $addChars;
                break;
        }
        if ($len > 10) {//位数过长重复字符串一定次数
            $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
        }
        $chars = str_shuffle($chars);
        $str = substr($chars, 0, $len);
        return $str;
    }
    
    /**
     +----------------------------------------------------------
     * 字符串截取，支持中文和其他编码
     +----------------------------------------------------------
     * @static
     +----------------------------------------------------------
     * @param string $str 需要转换的字符串
     * @param string $start 开始位置
     * @param string $length 截取长度
     * @param string $charset 编码格式
     * @param string $suffix 截断显示字符
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    public static function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
    {
            if(function_exists("mb_substr"))
                    return mb_substr($str, $start, $length, $charset);
            elseif(function_exists('iconv_substr')) {
                    return iconv_substr($str,$start,$length,$charset);
            }
            $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']	  = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']	  = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("",array_slice($match[0], $start, $length));
            if($suffix) return $slice."…";
            return $slice;
    }

    //大小写转化,默认小写
    public static function ChangCase($data,$lower = 'lower'){
        if($lower == 'lower')
            return array_change_key_case($data,CASE_LOWER);
        else
            return array_change_key_case($data,CASE_UPPER);
    }

    //日志记录
    public static function WriteLog($file, $msg) {
        $path = './Applications/shaizhong/Log/' . $file . '_' . date('Ymd') . '.log';
        $content = date('Y-m-d H:i:s') . ' ' . print_r($msg, true) . "\r\n";
        file_put_contents($path, $content, FILE_APPEND);
    }
    
    //金币变化日志
    public static function GoldLog($gold,$type=1,$purpose,$remark=''){
        global $db;
        $gold_log = [
            'username'  => $_SESSION['username'],
            'type'      => $type, //1 增加 2 减少
            'gold'      => $gold,
            'purpose'   => $purpose,
            'remark'    => $remark,
            'addtime'   => time(),
        ];
        $db->insert('sz_gold_log')->cols($gold_log)->query();
    }
    
    /**
    +----------------------------------------------------------
    * 通过GET方式获取远程路径数据
    +----------------------------------------------------------
    * @access public
    * @name get_curl
    +----------------------------------------------------------
    * @param string  $url 请求的URL地址
    +----------------------------------------------------------
    * @return void
    +----------------------------------------------------------
    */
    public static function get_curl($url){
        //$headers['CLIENT-IP'] = '60.12.204.203';
        //$headers['X-FORWARDED-FOR'] = '60.12.204.203';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        //curl_setopt ($ch, CURLOPT_HTTPHEADER , $headers );  //构造IP
        curl_setopt( $ch, CURLOPT_TIMEOUT, 20 );
        $result = curl_exec($ch);
        if(curl_errno($ch)){
            return curl_error($ch);
        }
        curl_close($ch);
        return $result;
    }
    
    //计算中奖号码
    public function CalcAwardNubmer($period){
        global $db;
        $config = $this->config;
        //获取投注奖金
        $betsum = $db->select('*')->from('sz_betsum')->orderByASC(array('awardmoney'),false)->query();
        //获取投注总额
        $betmoney = $period['betsum'];
        echo "投注总额：".$betmoney."\n";
        //获取配置
        $odds = $period['odds']/100;
        echo "返奖比率：".$odds."\n";
        //计算返奖金额
        $awardmoney = $betmoney * $odds;
        echo "返奖金额：".$awardmoney ."\n";
        $awardnumber_list = [];
        //中奖号码按中奖金额为键名排列
        foreach ($betsum as $val){
            $awardnumber_list[$val['awardmoney']][] = $val['awardmoney'];
        }
        print_r($awardnumber_list);
        //中奖号码只有一个的时候,向下在取一个,随机产生中奖号码
        $awardnumber_list_temp = [];
        $not_awardnumber = [];
        foreach ($awardnumber_list as $key => $value){
            //奖池金-基础奖池金-(总充值金额*20%)-中奖金额
            $awardpool_temp = $config['awardpool']-$config['basepool']-($config['paysum']*0.2)-$key;
            if($key < $awardmoney && $key > 0){
                $i++;
                if(count($value) > 1){
                    foreach ($value as $v){
                        $awardnumber_list_temp[$v['betnumber']] = $v;
                    }
                    break;
                }elseif($key < $awardmoney && $key > 0){
                    if($i <= 2){
                        foreach ($value as $v){
                            $awardnumber_list_temp[$v['betnumber']] = $v;
                        }
                    }
                }
            }
            
            //中奖与未中奖各一半
            if(count($awardnumber_list) == 2){
                if(count($value) == 28){
                    //判断奖池金够赔,取8个中奖号码随机开奖
                    if($awardpool_temp >= 0){
                        foreach ($value as $v){
                            if($v['awardmoney'] > 0){
                                $j++;
                                if($j <= 8){
                                    $awardnumber_list_temp[$v['betnumber']] = $v;
                                }
                            }
                            if($v['awardmoney'] <= 0){
                                $awardnumber_list_temp[$v['betnumber']] = $v;
                            }
                        }
                    }else{
                        //奖池金赔不起
                        if($key < $awardmoney){
                            foreach ($value as $v){
                                $awardnumber_list_temp[$v['betnumber']] = $v;
                            }
                        }
                    }
                }
            }
            echo $key."==============".$awardpool_temp."\n";
            if(!$awardnumber_list_temp){
                //奖池赔得起
                if($awardpool_temp >= 0){
                    array_push($not_awardnumber, $value);
                }
            }
            
        }
        echo "\n========第一种中奖号码===========\n";
        print_r($awardnumber_list_temp);
        echo "\n========第一种中奖号码===========\n";
        echo "\n========第二种中奖号码===========\n";
        print_r($not_awardnumber);
        echo "\n========第二种中奖号码===========\n";
        shuffle($awardnumber_list_temp);
        //中奖号码列表不为空
        if($awardnumber_list_temp){
            $award_number = $awardnumber_list_temp[array_rand($awardnumber_list_temp,1)];
        }elseif($not_awardnumber){
            foreach ($not_awardnumber as $value){
                foreach ($value as $val) {
                    $awardnumber_list_temp[] = $val;
                }
            }
            shuffle($awardnumber_list_temp);
            $award_number = $awardnumber_list_temp[array_rand($awardnumber_list_temp,1)];
        }else{
            //中奖号码列表为空,所有号码随机
            $award_number = $betsum[array_rand($betsum,1)];
        }
        echo "\n=============中奖号码=================\n";
        print_r($award_number);
        $awardnumber = substr($award_number['betnumber'],0,1).','.substr($award_number['betnumber'],1,1).','.substr($award_number['betnumber'],-1);
        $number = explode(',', $awardnumber);
        shuffle($number);
        $return = implode(',', $number);
        return $return;
    }
}
